package edu.auctionmart

import groovyx.net.http.HTTPBuilder
import org.joda.time.DateTime

class IvrService {

	void placeCall(String phoneNum, Auction theAuction, User user) {
		//should place different calls depending on whether auction is over or not
		println("Placing phone call")

		Auction auction = Auction.get(theAuction.id)

		Set<Bid> bids = auction.getBids()

		DateTime now = DateTime.now()
		DateTime end = auction.getEndTime()

		String winningUsername = ""
		String seller = ""

		if (now >= end) { //auction has ended, current bid should be the winning bid
			println(bids.size())

			if (auction.getWinner() == null && bids.size() > 0) { //first time setting winner
				println("Setting winner")
				Bid winningBid = auction.getCurrentBid()
				User winningUser = winningBid.getUserAccount()
				auction.setWinner(winningUser)
				auction.save(flush: true)
			}

			if (auction.getWinner() != null) {
				winningUsername = auction.getWinner().getUsername()
				if (user.getUsername() == winningUsername || user.getUsername() == "admin") {
					sendWonIVR(auction, phoneNum)
					return
				}
			}

			if (user.getUsername() == auction.getSeller().getUsername()) {
				if (auction.getWinner() != null) {
					sendSoldIVR(auction, phoneNum)
					return
				} else {
					sendUnsoldIVR(auction, phoneNum)
					return
				}
			}

			//Here the auction ended, the user had an e-mail alert, but they did not win
			sendDidNotWin(auction, phoneNum)
			return
		} else { //Informational notification
			sendInfo(auction, phoneNum, user)
			return
		}
	}


	void sendWonIVR(Auction auction, String phoneNum) {
		auction.refresh()
		String message = "won.xml"
		request(message, phoneNum)


	}

	void sendSoldIVR(Auction auction, String phoneNum) {
		auction.refresh()
		String message = "sold.xml"
		request(message, phoneNum)

	}

	void sendUnsoldIVR(Auction auction, String phoneNum ) {
		auction.refresh()
		String message = "didNotSell.xml"
		request(message, phoneNum)

	}

	void sendDidNotWin(Auction auction, String phoneNum) {
		auction.refresh()
		String message = "didNotWin.xml"
		request(message, phoneNum)

	}

	void sendInfo(Auction auction, String phoneNum, User username) {
		auction.refresh()
		String message = "reminder.xml"
		request(message, phoneNum)
	}

	private void request(String message, String phoneNum) {
		def http = new HTTPBuilder('http://api.voxeo.net')
		def response = http.get( path : '/SessionControl/4.5.41/CCXML10.start', query : [phonenum: phoneNum, vxml: message, timeout: '60s', cid: '0123456789', tokenid: '0858bc70143a994a9dfc42b066452d9b4a8bc96e15e6558aaa71bb1990d44e407c935af7e3958e2585b7be76'] )
	}

}
